package eerbaar.shared.persist.internal.lib;

import eerbaar.body.BodyFactory;
import eerbaar.body.IBrain;
import eerbaar.body.IHead;
import eerbaar.shared.exceptions.GameRuntimeException;
import eerbaar.shared.persist.IPersistService;
import eerbaar.shared.persist.IPersister;
import eerbaar.shared.persist.ISaver;
import eerbaar.shared.service.ServiceFactory;
import eerbaar.shared.tree.INode;


public class HeadPersister implements IPersister<IHead> {

    private IHead target;

    public HeadPersister() {
        //
    }

    public HeadPersister(IHead wrapper) {
        this.target = wrapper;
    }

    public HeadPersister(INode node) throws GameRuntimeException {
        load(node);
    }

    @Override
    public Class<IHead> getRegistertedInterface() {

        return IHead.class;
    }

    @Override
    public BrainPersister[] getSavableChildren() {

        BrainPersister p = new BrainPersister(this.target.getBrain());
        return new BrainPersister[] { p };
    }

    @Override
    public String getSavableName() {

        return "head";
    }

    @Override
    public IHead getTarget() {
        return this.target;
    }

    @Override
    public boolean isAssignableFrom(ISaver<?> savable) {
        return false;
    }

    @Override
    public IHead load(INode node) {
        assert (node != null);
        assert (node.getChildCount() == 1);

        IPersistService service = ServiceFactory
                .getService(IPersistService.class);
        IPersister<IBrain> p = service.getPersister(IBrain.class);
        IBrain brain = p.load(node.getChild(0));

        return BodyFactory.createHead(brain);
    }

    @Override
    public void saveAttributes(INode node) {
        //
    }

    @Override
    public void setTarget(IHead obj) {
        this.target = obj;
    }

}
